import React, { Component } from 'react'
import { StatusBar, DeviceEventEmitter, Linking, Platform, BackHandler,TouchableOpacity, Alert, ScrollView, View, Text, Image } from 'react-native'
import { List, ListItem } from 'react-native-elements'
import Icon from 'react-native-vector-icons/FontAwesome'
import { connect } from 'react-redux'
import { NavigationActions } from 'react-navigation'

//import { pay } from '../Lib/Alipay'
import Alipay from '../Lib/Alipay'
import * as WeChat from 'react-native-wechat'

import AlipayActions from '../Redux/AlipayRedux'

// Styles
import styles from './Styles/PayScreenStyle'

class PayScreen extends Component {
  static navigationOptions = {
    title: '在线支付'
  }
  constructor(props) {
    super(props)
    const { state } = this.props.navigation
    this.state = {
      payType: 'alipay',
      id: state.params.id,
      money: state.params.money
    }
  }
  componentDidMount() {
    Linking.addEventListener('url', this._handleOpenURL)
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
  }
  componentDidUpdate(prevProps, prevState) {
    if(prevProps.alipay.fetching && !this.props.alipay.error) {
      if(this.props.alipay.payType === 'alipay') {
        this.doAlipay()
      } else if(this.props.alipay.payType === 'wxpay') {
        this.doWxpay()
      }
    }
  }
  componentWillUnmount() {
    Linking.removeEventListener('url', this._handleOpenURL)
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  _handleOpenURL(event) {
    console.log(event.url)
    //console.log(this.navigator)
    //console.log(this.props)
    if (event.url.search(/9000/) > 0) {
      DeviceEventEmitter.emit('refreshOrderDetail')
      DeviceEventEmitter.emit('refreshOrderList')
      Alert.alert('支付成功')
    } else {
      Alert.alert('支付失败')
    }
    //this.navigator.dispatch(NavigationActions.back())
    //this.props.navigation.goBack()
  }
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }
  _getPay = () => {
    this.props.getPay(this.props.token, this.state.id, this.state.payType)
  }
  doAlipay() {
    const orderInfo = this.props.alipay.payload
    Alipay.pay(orderInfo).then((result) => {
      console.log(result)
      if(result.resultStatus == '9000') {
        Alert.alert('提示','支付成功')
        DeviceEventEmitter.emit('refreshOrderDetail')
        DeviceEventEmitter.emit('refreshOrderList')
        this.props.navigation.goBack()
      } else if (result.resultStatus == '8000') {
        Alert.alert('提示','支付结果确认中,请稍后查看')
      } else {
        Alert.alert('提示','支付失败')
      }
    }).catch((error) => console.error(error))
  }
  doWxpay() {
    const orderInfo = this.props.alipay.payload
    console.log(orderInfo)
    WeChat.pay(orderInfo).then((result) => {
      if(result.errCode == '0') {
        Alert.alert('提示','支付成功')
        DeviceEventEmitter.emit('refreshOrderDetail')
        DeviceEventEmitter.emit('refreshOrderList')
        this.props.navigation.goBack()
      } else {
        Alert.alert('提示','支付失败')
      }
    }).catch((error) => console.error(error))
  }
  render () {
    return (
      <View style={styles.container}>
        <StatusBar translucent={false} barStyle='dark-content' backgroundColor='white' />
        <ScrollView style={{flex:1}}>
          <View style={styles.section}>
            <Text style={styles.money}>￥{this.state.money}</Text>
          </View>
          <Text style={{marginBottom:5,marginLeft:5}}>选择支付方式</Text>
          <View style={styles.list}>
            <TouchableOpacity
              onPress={()=>this.setState({payType:'alipay'})}
              style={styles.listItem}>
              <View style={styles.listItemLeft}>
                <Image source={require('../Images/alipay.png')}
                  style={styles.listItemImage} />
                <View style={styles.listItemMain}>
                  <Text style={styles.listItemTitle}>
                    支付宝<Text style={styles.label}></Text></Text>
                  <Text style={styles.listItemDesc}>推荐使用支付宝</Text>
                </View>
              </View>
              {this.state.payType === 'alipay' &&
              <View>
                <Icon
                  name='check-circle'
                  style={styles.listItemRightIcon} />
              </View>}
            </TouchableOpacity>
            <TouchableOpacity
              onPress={()=>this.setState({payType:'wxpay'})}
              style={styles.listItem}>
              <View
                style={styles.listItemLeft}>
                <Image source={require('../Images/wechat.png')}
                  style={styles.listItemImage} />
                <View style={styles.listItemMain}>
                  <Text style={styles.listItemTitle}>
                    微信支付<Text style={styles.label}></Text></Text>
                </View>
              </View>
              {this.state.payType === 'wxpay' &&
              <View>
                <Icon
                  name='check-circle'
                  style={styles.listItemRightIcon} />
              </View>}
            </TouchableOpacity>
          </View>
        </ScrollView>
        <TouchableOpacity
          onPress={this._getPay}
          style={styles.footer}>
          <Text style={styles.footerText}>确认支付</Text>
        </TouchableOpacity>
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    token: state.user.payload.token,
    alipay: state.alipay
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getPay: (token,id,payType) => dispatch(AlipayActions.alipayRequest(token,id,payType))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(PayScreen)
